<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="versionCode">
        <el-input
          v-model="queryParams.versionCode"
          placeholder="请输入版本号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新状态" prop="updateStatus">
        <el-select v-model="queryParams.updateStatus" placeholder="请选择更新状态" clearable>
          <el-option label="检查更新" value="CHECK" />
          <el-option label="开始下载" value="DOWNLOAD_START" />
          <el-option label="下载完成" value="DOWNLOAD_COMPLETE" />
          <el-option label="安装成功" value="INSTALL_SUCCESS" />
          <el-option label="安装失败" value="INSTALL_FAILED" />
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['version:updateLogs:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['version:updateLogs:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="updateLogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceId" />
      <el-table-column label="设备型号" align="center" prop="deviceModel" />
      <el-table-column label="当前版本" align="center" prop="currentVersion" />
      <el-table-column label="目标版本" align="center" prop="targetVersion" />
      <el-table-column label="更新状态" align="center" prop="updateStatus">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.updateStatus)">
            {{ getStatusText(scope.row.updateStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMessage" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            link
            type="primary"
            icon="TrendCharts"
            @click="handleTrack(scope.row)"
          >轨迹</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['version:updateLogs:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 更新日志详情对话框 -->
    <el-dialog title="更新日志详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备ID">{{ detailForm.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ detailForm.deviceModel }}</el-descriptions-item>
        <el-descriptions-item label="系统版本">{{ detailForm.osVersion }}</el-descriptions-item>
        <el-descriptions-item label="应用版本">{{ detailForm.appVersion }}</el-descriptions-item>
        <el-descriptions-item label="当前版本">{{ detailForm.currentVersion }}</el-descriptions-item>
        <el-descriptions-item label="目标版本">{{ detailForm.targetVersion }}</el-descriptions-item>
        <el-descriptions-item label="更新状态">
          <el-tag :type="getStatusType(detailForm.updateStatus)">
            {{ getStatusText(detailForm.updateStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ detailForm.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="用户代理">{{ detailForm.userAgent }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">{{ detailForm.errorMessage || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 设备更新轨迹对话框 -->
    <el-dialog title="设备更新轨迹" v-model="trackOpen" width="1000px" append-to-body>
      <el-timeline>
        <el-timeline-item
          v-for="item in trackList"
          :key="item.id"
          :timestamp="parseTime(item.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')"
          :type="getTimelineType(item.updateStatus)"
        >
          <el-card>
            <h4>{{ getStatusText(item.updateStatus) }}</h4>
            <p>版本：{{ item.currentVersion }} → {{ item.targetVersion }}</p>
            <p v-if="item.errorMessage" class="error-message">错误信息：{{ item.errorMessage }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup name="UpdateLogs">
import { listUpdateLogs, getUpdateLog, delUpdateLog, getDeviceUpdateTrack } from "@/api/version/updateLogs";

const { proxy } = getCurrentInstance();

const updateLogList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const detailOpen = ref(false);
const trackOpen = ref(false);
const detailForm = ref({});
const trackList = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: null,
    versionCode: null,
    updateStatus: null,
    beginTime: null,
    endTime: null
  }
});

const { queryParams } = toRefs(data);

/** 查询更新日志列表 */
function getList() {
  loading.value = true;
  queryParams.value.beginTime = dateRange.value ? dateRange.value[0] : null;
  queryParams.value.endTime = dateRange.value ? dateRange.value[1] : null;
  listUpdateLogs(queryParams.value).then(response => {
    updateLogList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
}

/** 详情按钮操作 */
function handleDetail(row) {
  getUpdateLog(row.id).then(response => {
    detailForm.value = response.data;
    detailOpen.value = true;
  });
}

/** 轨迹按钮操作 */
function handleTrack(row) {
  getDeviceUpdateTrack(row.deviceId).then(response => {
    trackList.value = response.data;
    trackOpen.value = true;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const logIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除更新日志编号为"' + logIds + '"的数据项？').then(function() {
    return delUpdateLog(logIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('app/update-logs/export', {
    ...queryParams.value
  }, `update_logs_${new Date().getTime()}.xlsx`)
}

// 获取状态类型
function getStatusType(status) {
  const statusMap = {
    'CHECK': 'info',
    'DOWNLOAD_START': 'warning',
    'DOWNLOAD_COMPLETE': 'primary',
    'INSTALL_SUCCESS': 'success',
    'INSTALL_FAILED': 'danger'
  };
  return statusMap[status] || 'info';
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    'CHECK': '检查更新',
    'DOWNLOAD_START': '开始下载',
    'DOWNLOAD_COMPLETE': '下载完成',
    'INSTALL_SUCCESS': '安装成功',
    'INSTALL_FAILED': '安装失败'
  };
  return statusMap[status] || status;
}

// 获取时间线类型
function getTimelineType(status) {
  const typeMap = {
    'CHECK': 'primary',
    'DOWNLOAD_START': 'warning',
    'DOWNLOAD_COMPLETE': 'info',
    'INSTALL_SUCCESS': 'success',
    'INSTALL_FAILED': 'danger'
  };
  return typeMap[status] || 'primary';
}

getList();
</script>

<style scoped>
.error-message {
  color: #f56c6c;
  margin: 0;
}
</style>